package com.one.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.one.pojo.SysUser;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Description  后台用户登陆过滤器
 * @Author semstouch
 * @Date 2017/5/6
 **/
@Component("webFilter")
public class WebFilter implements Filter {
    protected static final org.slf4j.Logger logger = LoggerFactory.getLogger(WebFilter.class);
    protected FilterConfig filterConfig;



    public void destroy() {
        filterConfig = null;
    }

    public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) {
        HttpServletRequest req = (HttpServletRequest) arg0;
        String uri = req.getRequestURI();
        String realUri = uri.replace(req.getContextPath().toString(), "");
        String accept = req.getHeader("Accept");

        if (isAuth(realUri)) {
            SysUser sysuser = (SysUser) req.getSession().getAttribute("sysuser");
            if (sysuser == null) {
                if (accept.contains("application/json")) {
                    loginJsonPath(arg0, arg1, arg2);
                } else {
                    loginPath(arg0, arg1, arg2);
                }
            } else {
                commonPath(arg0, arg1, arg2);
            }
        } else {
            commonPath(arg0, arg1, arg2);
        }
    }


    public void loginPath(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) {
        String loginPath = "/rest/web/toLogin";
        RequestDispatcher loginDispatcher = arg0.getRequestDispatcher(loginPath);
        try {
            loginDispatcher.forward(arg0, arg1);
        } catch (ServletException e) {
            logger.error(e.toString());
        } catch (IOException e) {
            logger.error(e.toString());
        }
    }

    public void loginJsonPath(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) {
        JSONResult jsonResult = new JSONResult();
        jsonResult.setCode("403");
        jsonResult.setMsg("用户未登录，请重新登陆!");
        ObjectMapper mapper = new ObjectMapper();
        String rs = "";
        try {
            rs = mapper.writeValueAsString(jsonResult);
        } catch (Exception e) {
            logger.error(e.toString());
        }
        arg1.setCharacterEncoding("UTF-8");
        arg1.setContentType("application/json; charset=utf-8");
        try {
            PrintWriter out = arg1.getWriter();
            out.write(rs);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断URL是否需要被过滤
     * 2016-8-2下午7:28:06
     * zhuangjf
     */
    public boolean isAuth(String realUri) {
        boolean noAuth = !realUri.matches("(/rest|rest)/web/toLogin|(/rest|rest)/web/login");
        return noAuth;
    }

    public void commonPath(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) {
        try {
            arg2.doFilter(arg0, arg1);
        } catch (IOException e) {
            logger.error(e.toString());
        } catch (ServletException e) {
            logger.error(e.toString());
        }
        return;
    }

    public void init(FilterConfig fConfig) throws ServletException {
        filterConfig = fConfig;
    }
}